<route lang="json5">
{
  style: { navigationBarTitleText: '订单中心', navigationStyle: 'custom' }
}
</route>

<template>
  <view>
    <view>

      <!-- 顶部 Tabs -->
      <view class="tabs bg-white border-b border-gray-200">
        <view class="tab" :class="{ active: tab === 'publish' }" @click="tab = 'publish'">发单</view>
        <view class="tab" :class="{ active: tab === 'list' }" @click="tab = 'list'">接单列表</view>
        <view class="tab" :class="{ active: tab === 'mine' }" @click="tab = 'mine'">我的订单</view>
        <view class="tab-notice" @click="showNoticePanel = !showNoticePanel">
          通知 <view v-if="unreadCount" class="dot-badge">{{ unreadCount }}</view>
        </view>
      </view>

      <!-- 通知面板 -->
      <transition name="fade">
        <view v-if="showNoticePanel" class="notice-panel">
          <view v-if="!notices.length" class="p-3 text-gray-500 text-sm">暂无通知</view>
          <view v-else class="max-h-48 overflow-y-auto">
            <view v-for="n in notices" :key="n.id" class="p-3 border-b border-gray-100">
              <view class="text-[14px]">{{ n.message }}</view>
              <view class="text-[12px] text-gray-500">{{ formatTime(n.time) }}</view>
            </view>
          </view>
          <view class="p-2 text-right">
            <wd-button size="small" plain @click="markAllRead">全部已读</wd-button>
          </view>
        </view>
      </transition>

      <!-- 主内容区 -->
      <view style="height: calc(100dvh - 122px);">
        <!-- 发单 -->
        <scroll-view v-if="tab === 'publish'" class="h-full" scroll-y>
          <view class="card">
            <view class="field">
              <view class="label">服务类型</view>
              <picker mode="selector" :range="serviceTypes" @change="onSvcChange">
                <view class="picker">{{ form.type || '请选择服务类型' }}</view>
              </picker>
            </view>

            <view class="field">
              <view class="label">价格（元）</view>
              <input class="input" type="number" v-model="form.price" placeholder="请输入价格，如 99" />
            </view>

            <view class="field">
              <view class="label">服务地址</view>
              <input class="input" v-model="form.address" placeholder="请输入地址" />
            </view>

            <view class="field">
              <view class="label">联系方式</view>
              <input class="input" v-model="form.contact" placeholder="请输入联系方式" />
            </view>

            <view class="pt-2">
              <wd-button type="primary" :loading="publishing" @click="submitOrder">
                {{ publishing ? '提交中…' : '提交订单' }}
              </wd-button>
            </view>
          </view>

          <view v-if="myPending.length" class="mt-4">
            <view class="text-xs text-gray-500 px-1 mb-1">我发布的待接单</view>
            <view class="space-y-2">
              <view v-for="o in myPending" :key="o.id" class="card">
                <view class="title">{{ o.type }} · ¥{{ o.reward }}</view>
                <view class="meta">地址：{{ o.address }}</view>
                <view class="meta" v-if="o.remark">备注：{{ o.remark }}</view>
                <view class="meta">状态：{{ o.status }}</view>
                <view class="meta">下单：{{ formatTime(o.crtim) }}</view>
                <view class="mt-2 flex gap-2" v-if="!['已支付', '完成', '取消'].includes(o.status)">
                  <wd-button size="small" type="warning" plain @click="cancel(o)">取消</wd-button>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>

        <!-- 接单列表 -->
        <scroll-view v-else-if="tab === 'list'" class="h-full" scroll-y :refresher-enabled="true"
          :refresher-triggered="refreshing" refresher-background="#f7f8fa" @refresherrefresh="onRefresh">
          <view class="text-xs text-gray-500 px-1 mb-2">以下为待接单订单</view>

          <view v-for="o in pendingOrders" :key="o.id" class="card">
            <view class="title">{{ o.type }} · ¥{{ o.reward }}</view>
            <view class="meta">地址：{{ o.address }}</view>
            <view class="meta">联系方式：{{ o.contact }}</view>
            <view class="meta">发布者：{{ o.crman }}</view>
            <view class="meta">状态：{{ o.status }}</view>
            <view class="meta">下单：{{ formatTime(o.crtim) }}</view>
            <view class="mt-2 flex gap-2">
              <wd-button size="small" plain @click="preview(o)">查看</wd-button>
              <wd-button size="small" type="primary" :disabled="takingId === o.id" @click="take(o)">
                {{ takingId === o.id ? '接单中…' : '接单' }}
              </wd-button>
            </view>
          </view>

          <view v-if="!pendingOrders.length" class="card text-gray-500">暂无</view>
        </scroll-view>

        <!-- 我的订单 -->
        <scroll-view v-else class="h-full" scroll-y>
          <view v-if="myPending.length" class="mb-4">
            <view class="text-xs text-gray-500 px-1 mb-1">我的订单</view>
            <view class="space-y-2">
              <view v-for="o in myPending" :key="o.id" class="card">
                <view class="title">{{ o.type }} · ¥{{ o.reward }}</view>
                <view class="meta">地址：{{ o.address }}</view>
                <view class="meta">联系方式：{{ o.contact }}</view>
                <view class="meta">状态：{{ o.status }}</view>
                <view class="meta">下单：{{ formatTime(o.crtim) }}</view>
                <view class="mt-2 flex gap-2" v-if="!['已支付', '完成', '取消'].includes(o.status)">
                  <wd-button size="small" type="warning" plain @click="cancel(o)">取消</wd-button>
                </view>
              </view>
            </view>
          </view>

          <view v-if="myPending.length" class="mb-4">
            <view class="text-xs text-gray-500 px-1 mb-1">已接单 / 服务中</view>
            <view class="space-y-2">
              <view v-for="o in filteredPending()" :key="o.id" class="card">
                <view class="title">{{ o.type }} · ¥{{ o.reward }}</view>
                <view class="meta">地址：{{ o.address }}</view>
                <view class="meta" v-if="o.remark">备注：{{ o.remark }}</view>
                <view class="meta">状态：{{ o.status }}</view>
                <view class="meta">下单：{{ formatTime(o.crtim) }}</view>
                <view class="mt-2 flex gap-2">
                  <wd-button
                    v-if="['待支付'].includes(o.status)"
                    size="small"
                    type="success"
                    plain
                    @click="pay(o)"
                  >支付</wd-button>

                  <wd-button
                    v-if="['已支付'].includes(o.status)"
                    size="small"
                    type="primary"
                    plain
                    @click="finish(o)"
                  >确认完成</wd-button>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { getAvailableOrders, getAvailableOrdersUser, availableOrdersPost, availableOrdersPut } from '@/api/allApi'
const userInfoStr = localStorage.getItem('userInfo') || '{}'
const userInfo = JSON.parse(userInfoStr)
/* ---------- 基础 ---------- */
const currentUserId = 'user_me_001'

/* --------- Tab/通知 --------- */
const tab = ref<'publish' | 'list' | 'mine'>('publish')
const showNoticePanel = ref(false)
type Notice = { id: string; message: string; time: number; read?: boolean }
const notices = ref<Notice[]>([])
const unreadCount = computed(() => notices.value.filter(n => !n.read).length)
const markAllRead = () => {
  notices.value.forEach(n => (n.read = true))
  notices.value = notices.value.slice()
}

function filteredPending() {
  const validStatuses = ['待支付', '已支付'];
  return myPending.value.filter(o => validStatuses.includes(o.status));
}

/* ---------- 订单&支付类型 ---------- */
type PayStatus = 'unpaid' | 'paid' | 'released'
interface Order {
  id: string; type: string; price: number; address: string; contact?: string
  status: string; creatorId: string; takerId?: string; createdAt: number
  payStatus: PayStatus; paidAt?: number; releasedAt?: number
}

const TX_KEY      = 'demo_pay_tx_v1'

/* ---------- 简易钱包 & 交易记录（仅演示记录，不做真实扣款） ---------- */
type Tx = { id: string; orderId: string; type: 'pay' | 'release'; amount: number; from?: string; to?: string; time: number }
const txs = ref<Tx[]>([])

function saveTxs() { uni.setStorageSync(TX_KEY, JSON.stringify(txs.value)) }

/* ---------- WebSocket Mock ---------- */
type WSMsg = { to: string; event: string; message: string }
function createMockWS() {
  const ls: Function[] = []
  return { onMessage: (cb: Function) => ls.push(cb), push: (m: WSMsg) => ls.forEach(cb => cb(m)) }
}
const ws = createMockWS()

/* ---------- 表单 ---------- */
const serviceTypes = ['外卖', '快递', '代办']
const form = reactive({ type: '', price: 0, address: '', contact: '', status: '' })
const publishing = ref(false)
function onSvcChange(e: any) { form.type = serviceTypes[e.detail.value] }
async function submitOrder() {
  if (!form.price) return toast('请输入价格')
  if (!form.address) return toast('请输入地址')
  if (!form.contact) return toast('请输入联系方式')
  if (!form.type) return toast('请选择服务类型')
  publishing.value = true
  availableOrdersPost(form.type, form.price, form.address, '待接单', form.contact, userInfo?.data?.id).then((res) => {
    updateData()
  })
  publishing.value = false
  Object.assign(form, { type: '', price: '', address: '', remark: '' })
  toast('提交成功')
}

/* ---------- 接单 ---------- */
const refreshing = ref(false); const takingId = ref<string>()
const pendingOrders = ref([])
const myPending = ref([])

function preview(o: Order) {
  uni.showModal({
    title: `${o.type} · ¥${o.reward}`,
    content: `地址：${o.address}\n备注：${o.contact || '—'}\n状态：${o.status}`
    // content: `地址：${o.address}\n备注：${o.contact || '—'}\n状态：${o.status}\n支付：${payText(o)}`
  })
}
async function take(o: Order) {
  availableOrdersPut(o.type, o.id, '待支付', o.price, o.address, o.contact, userInfo?.data?.id, o.reward).then((res) => {
    updateData()
  })
  // ws.push({ to: o.creatorId, event: 'ORDER_TAKEN', message: `您的订单（${o.serviceType}）已被接单，请尽快完成支付托管` })
}
function onRefresh() { refreshing.value = true; setTimeout(() => { loadOrders(); refreshing.value = false }, 400) }

/* ---------- 我的订单 ---------- */
function cancel(o: Order) { 
  availableOrdersPut(o.type, o.id, '取消', o.price, o.address, o.contact, userInfo?.data?.id, o.reward).then((res) => {
    updateData()
  })
}

/* ---------- 支付&放款（托管模拟） ---------- */
async function pay(o: Order) {
  uni.showLoading({ title: '支付中…' })
  await sleep(600)
  uni.hideLoading()

  availableOrdersPut(o.type, o.id, '已支付', o.price, o.address, o.contact, userInfo?.data?.id, o.reward).then((res) => {
    updateData()
  })

  // 仅记录：标记为已支付（托管中）
  o.payStatus = 'paid'
  o.paidAt = Date.now()

  // 交易记录（演示）
  txs.value.unshift({ id: uid('tx'), orderId: o.id, type: 'pay', amount: o.price, from: o.creatorId, time: Date.now() })
  saveTxs()

  // 通知接单方
  ws.push({ to: o.takerId, event: 'ORDER_PAID', message: `订单（${o.type}）已托管支付 ¥${o.price}` })
  toast('支付成功，已托管')
}

function finish(o: Order) {
  
  availableOrdersPut(o.type, o.id, '完成', o.price, o.address, o.contact, userInfo?.data?.id, o.reward).then((res) => {
    updateData()
  })
  toast('已完成')
  // 完成后提示是否评价对方
  uni.showActionSheet({
    itemList: ['我要评价对方'],
    success: () => {
      showReviewDialog(o)
    }
  })
}

function showReviewDialog(order: Order) {
  const isCreator = order.creatorId === userInfo?.data?.id
  const revieweeId = isCreator ? order.takerId : order.creatorId
  const defaultReview = {
    rating: 5,
    content: ''
  }

  // 使用自定义弹窗或页面跳转，这里用 modal 模拟
  uni.showModal({
    title: '评价对方',
    content: '请打分并留下宝贵意见',
    editable: true,
    placeholderText: '请输入评价内容...',
    success: function (res) {
      if (!res.confirm) return

      const content = res.content.trim() || '用户没有填写评价'
      const rating = defaultReview.rating

      if (!revieweeId) return toast('无法确定被评用户')

      // 提交评论（模拟）
      addReview({
        orderId: order.id,
        rating,
        content,
        reviewerId: userInfo?.data?.id,
        revieweeId,
        time: Date.now()
      })

      toast('评价成功')
      updateData() // 刷新订单数据
    }
  })
}

/* ---------- 工具 ---------- */
function uid(p = 'id') { return `${p}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}` }
const sleep = (ms: number) => new Promise(r => setTimeout(r, ms))
const toast = (t: string) => uni.showToast({ title: t, icon: 'none' })
function formatTime(ts: number) { const d = new Date(ts); return `${d.getMonth() + 1}-${d.getDate()} ${d.getHours()}:${String(d.getMinutes()).padStart(2, '0')}` }
// function payText(o: Order) { return ({ "待接单": '未支付', paid: '已托管', released: '已放款' } as Record<PayStatus, string>)[o.payStatus] }

function updateData() {
  try {
    getAvailableOrders('待接单').then((res) => {
      pendingOrders.value = res.data.items
    })
    getAvailableOrdersUser(userInfo?.data?.id).then((res) => {
      myPending.value = res.data.items
    })
  } catch {
    
  }
}

/* ---------- 生命周期 ---------- */
onMounted(() => {
  updateData()

  ws.onMessage((m: WSMsg) => {
    if (m.to !== currentUserId) return
    notices.value.unshift({ id: uid('n'), message: m.message, time: Date.now() })
  })
})
</script>

<style lang="scss" scoped>
.fade-enter-active,
.fade-leave-active {
  transition: .18s all ease
}
.fade-enter-from { opacity: 0; transform: translateY(-4px) }
.fade-leave-to   { opacity: 0; transform: translateY(-4px) }

.tabs {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px 12px
}
.tab {
  padding: 8px 12px;
  background: #f3f4f6;
  border-radius: 10px;
  font-size: 14px
}
.tab.active {
  background: #2563eb;
  color: #fff;
  box-shadow: 0 2px 8px rgba(37, 99, 235, .25)
}
.tab-notice {
  margin-left: auto;
  padding: 8px 12px;
  border: 1px solid #e5e7eb;
  border-radius: 10px;
  position: relative
}
.dot-badge {
  position: absolute;
  top: -6px;
  right: -6px;
  background: #ef4444;
  color: #fff;
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 999px
}
.notice-panel {
  position: absolute;
  right: 10px;
  top: 92px;
  width: 260px;
  background: #fff;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, .06);
  z-index: 20
}
.card {
  background: #fff;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  padding: 12px;
  margin: 10px 12px;
}
.title { font-weight: 600; font-size: 15px }
.meta { font-size: 13px; color: #6b7280; margin-top: 2px }
</style>
